<template>
  <div class="changepwd">
    <el-card class="login-container">
      <div slot="header" class="login-title"><p>修改密码</p></div>
      <el-form
        ref="loginForm"
        status-icon
        :model="Form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="Form.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="oldpwd">
          <label slot="label">旧密码</label>
          <el-input
            type="password"
            v-model="Form.oldpwd"
            show-password
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="newpwd">
          <label slot="label">新密码</label>
          <el-input
            type="password"
            v-model="Form.newpwd"
            show-password
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <!-- 验证码组件 -->
        <el-form-item class="verifycode" label="验证码" prop="verifycode">
          <el-input
            v-model="Form.verifycode"
            placeholder="不区大小写"
          ></el-input>
          <verify-code @getIdentifyCode="getCode" :key="timer"></verify-code>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" size="small" @click="changepwd()">
            修改密码
          </el-button>

          <el-button size="small" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import VerifyCode from '../Login/VerifyCode.vue'
export default {
  name: 'Login',
  components: {
    VerifyCode,
  },
  computed: mapState(['userName']),
  data() {
    /* 自定义用户名的校验规则 */
    var checkUesrname = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'))
      } else {
        this.$http.post('/user/username', { user_name: value }).then(res => {
          const { code } = res
          if (code == 0) {
            callback()
          } else {
            return callback(new Error('该用户不存在！无法修改密码'))
          }
        })
      }
    }

    var checkOldpwd = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('旧密码不能为空'))
      } else {
        if (this.Form.username) {
          this.$http
            .post('/user/username', { user_name: this.Form.username })
            .then(res => {
              const { user_password, user_id } = res.result
              this.userid = user_id
              if (user_password == this.Form.oldpwd) {
                callback()
              } else {
                return callback(new Error('旧密码错误'))
              }
            })
        } else {
          return callback(new Error('请输入用户名！'))
        }
      }
    }
    var checkNewpwd = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('新密码不能为空'))
      } else {
        if (value == this.Form.oldpwd) {
          return callback(new Error('旧密码不能和新密码一直'))
        } else {
          callback()
        }
      }
    }
    /* 自定义验证码的校验规则 */
    var checkCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('验证码不能为空'))
      } else if (value.toLowerCase() !== this.realCode) {
        callback(new Error('验证码错误'))
      } else {
        callback()
      }
    }
    return {
      realCode: '', //验证码图片上的真实验证码
      timer: '', //定义一个时间戳用于重新加载验证码组件，原理是给验证码组件绑定一个:key
      // 只要key发生变化，则子组件重新渲染
      userid: '', //数据库表中的user_id
      Form: {
        username: '',
        oldpwd: '',
        newpwd: '',
        verifycode: '',
      },
      rules: {
        username: [{ validator: checkUesrname, trigger: 'blur' }],
        oldpwd: [{ validator: checkOldpwd, trigger: 'blur' }],
        newpwd: [{ validator: checkNewpwd, trigger: 'blur' }],
        verifycode: [{ validator: checkCode, trigger: 'blur' }],
      },
    }
  },

  methods: {
    changepwd() {
      // 校验表单
      this.$refs['loginForm'].validate(valid => {
        if (valid) {
          // 表单验证成功则发送用户id和新密码修改密码
          const userInfo = {
            user_name: this.Form.username,
            user_password: this.Form.newpwd,
          }
          this.$http.put(`/user/${this.userid}`, userInfo).then(res => {
            const { code } = res
            if (code == 0) {
              this.$confirm('密码已修改，是否登陆该账号?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
              })
                .then(() => {
                  this.$http
                    .post('/login', {
                      username: this.Form.username,
                      password: this.Form.newpwd,
                    })
                    .then(res => {
                      const { code, msg, userType } = res
                      if (code == 0) {
                        // 将数据库生成的token存放在浏览器的localStorage属性中
                        window.localStorage.setItem('token', res.token)
                        if (userType == 'user') {
                          this.$store.commit('defUserType', true)
                        } else if (userType == 'traffic') {
                          this.$store.commit('defUserType', false)
                        }
                        this.timer = new Date().getTime()
                        this.$router.push('/')
                      } else {
                        this.$message.error(msg)
                        // 当登录失败要改变验证码
                        this.timer = new Date().getTime()
                      }
                    })
                })
                .catch(() => {
                  this.$message({
                    type: 'info',
                    message: '已取消登录该用户',
                  })
                  this.$router.push('/')
                })
            }
          })
        } else {
        }
      })
    },
    reset() {
      this.Form.username = ''
      this.Form.password = ''
      this.Form.verifycode = ''
    },

    getCode(code) {
      this.realCode = code
    },
  },
  mounted() {
    this.Form.username = this.userName
  },
}
</script>

<style>
.changepwd {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  background-image: url('img/login.gif');
  background-repeat: no-repeat;
  background-size: cover;
}
.login-container {
  height: 400px;
  width: 400px;
  background: rgba(172, 219, 83, 0.6);
}
.el-card__header {
  height: 10%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgb(255, 69, 0) !important;
}
.login-title {
  height: 60px;
  width: 400px;
  display: flex;
  align-items: center;
}
.login-title p {
  font-size: 22px;
  font-weight: 900;
  color: white;

  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-card__body {
  width: 100%;
  height: 400px;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
}
.el-form-item__label {
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
}
.verifycode {
  display: flex;
  align-items: center;
  justify-content: center;
}

.verifycode .el-form-item__content {
  width: 280px !important;
  height: 45px !important;
  margin: 0 !important;
  padding: 0 !important;
  display: flex;
  align-items: center;
  justify-content: center;
}
.verifycode input {
  width: 150px;
}
.align {
  width: 50px;
}
.btns {
  height: 45px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.btns .el-form-item__content {
  margin: 0 !important;
  padding: 0 !important;
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.btns button:hover {
  text-decoration: underline;
  font-weight: 900;
}

/* 输入框右边的绿色勾勾 */
.el-input__suffix {
  color: rgb(48, 242, 48);
  font-weight: 900;
}
</style>
